package soduku.drutt.com;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;

import java.util.Random;

@SuppressWarnings("serial")
public class Sudoku extends JFrame implements KeyListener, ActionListener {
    
    private int size = 333;
    private JTextField[][] numberFields = new JTextField[9][9];
    private MyInteger[][] boxes    = new MyInteger[9][9];
    private MyInteger[][] rader    = new MyInteger[9][9];
    private MyInteger[][] kolumner = new MyInteger[9][9];
    
    JButton calculateBTN, resetBTN, lastBTN;
    
	public Sudoku() {
        setLayout(new BorderLayout());
        JPanel sud = new JPanel();
        sud.setLayout(new GridLayout(3, 3));
        add(sud, BorderLayout.CENTER);
        
        JPanel knapp = new JPanel();
        knapp.setLayout(new GridLayout(1,3));
        add(knapp, BorderLayout.SOUTH);
        
        resetBTN = new JButton("Reset");
        resetBTN.addActionListener(this);
        resetBTN.setEnabled(false);
        knapp.add(resetBTN);
        
        calculateBTN = new JButton("Calculate");
        calculateBTN.addActionListener(this);
        knapp.add(calculateBTN);
        
        lastBTN = new JButton("Last");
        lastBTN.addActionListener(this);
        lastBTN.setEnabled(false);
        knapp.add(lastBTN);

		for (int i = 0; i <= 8; i++) {
			JPanel temp = new JPanel();
			temp.setLayout(new GridLayout(3, 3));
			temp.setBorder(new LineBorder(Color.black));
			sud.add(temp);
			
			for (int j = 0; j <= 8; j++) {
				JTextField tempText = new JTextField();
				tempText.addKeyListener(this);
				tempText.setHorizontalAlignment(tempText.CENTER);
				numberFields[i][j] = tempText;
				temp.add(tempText);
			}
			
		}
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setSize(new Dimension(size, size + 30 + calculateBTN.getSize().height));
		setTitle("Sudoku Solver");
		setVisible(true);
		getRandomStartUp();
		
	}
	
	
	private void getRandomStartUp() {
	    Random num = new Random();
	    Random index = new Random();
	    
        for (int i = 0; i <= 8; i++) {
            int j = index.nextInt(9);
            numberFields[i][j].setText((num.nextInt(9) + 1) + "");
        }
        repaint();
	}
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new Sudoku();

	}
    @Override
    public void keyPressed(KeyEvent e) {
        resetBTN.setEnabled(true);
        JTextField textField = (JTextField) e.getSource();
        textField.setText("");
        textField.setEditable(false);
        textField.setEditable(true);
        String text = textField.getText();
        int key = e.getKeyCode();
        
        if (key >= 49 && key <=57) {
            //textField.setText("" + (key - 48));
        } else {
            textField.setText("");
        }

        /*if (text.length() == 0) {
            ;
        } else {
            Character first = text.charAt(0);
            if (!Character.isDigit(first) || first == '0') {
                textField.setText("");
            } else {
                textField.setText(first.toString());
            }
        }*/   
    }
    
    @Override
    public void keyReleased(KeyEvent e) {
        JTextField textField = (JTextField) e.getSource();
        String text = textField.getText();
        if (text.length() == 0) {
            ;
        } else {
            Character first = text.charAt(0);
            if (!Character.isDigit(first) || first == '0') {
                textField.setText("");
            }
        }
    }
    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        //JButton btn = (JButton) e.getSource();
        //btn.setEnabled(false);
        if (e.getSource() == calculateBTN) {
            
            resetBTN.setEnabled(true);
            
            for (int i = 0; i <= 8; i++) {
                for (int j = 0; j <= 8; j++) {
                    String text = numberFields[i][j].getText();
                    //textRutor[i][j].setEditable(false);
                    
                    int storKol = (i % 3) * 3;
                    int storRad = (i / 3) * 3;
                    
                    int lillKol = (j % 3);
                    int lillRad = (j / 3);
                    
                    int kol = storKol + lillKol;
                    int rad = storRad + lillRad;
                    
                    MyInteger temp = null;
                    
                    if (text.length() == 0) {
                        temp = new MyInteger(0);
                        numberFields[i][j].setBackground(Color.white);
                        numberFields[i][j].setForeground(Color.black);
                    } else {
                        temp = new MyInteger(Integer.parseInt(text));
                        numberFields[i][j].setBackground(Color.black);
                        numberFields[i][j].setForeground(Color.white);
                    }
                    boxes[i][j]        = temp;
                    kolumner[kol][rad] = temp;
                    rader[rad][kol]    = temp;
    
                }
            }
            
            Solver solver = new Solver(boxes, rader, kolumner, numberFields);
            
            if (!solver.possibleSudoku()) {
                JOptionPane.showMessageDialog(null, "No solution", "No solution",
                        JOptionPane.ERROR_MESSAGE);
            } else if (solver.isFinished()) {
                JOptionPane.showMessageDialog(null, "Allready done", "No solution",
                        JOptionPane.ERROR_MESSAGE);
            } else {
                
                MyInteger[][] svar = solver.solve();
                
                if (svar == null) {
                    JOptionPane.showMessageDialog(null, "No solution!!!!!!!!", 
                            "No solution", JOptionPane.ERROR_MESSAGE);
                } else {        
                    for (int i = 0; i <= 8; i++) {
                        for (int j = 0; j <= 8; j++) {
                            numberFields[i][j].setText(svar[i][j].toString());
                        }
                    }
                }
            }
            
            lastBTN.setEnabled(true);
            
        } else if (e.getSource() == resetBTN) {
            resetBTN.setEnabled(false);
            for (int i = 0; i <= 8; i++) {
                for (int j = 0; j <= 8; j++) {
                    numberFields[i][j].setBackground(Color.white);
                    numberFields[i][j].setForeground(Color.black);
                    numberFields[i][j].setText("");
                }
            }
        } else if (e.getSource() == lastBTN) {
            for (int i = 0; i <= 8; i++) {
                for (int j = 0; j <= 8; j++) {
                    if (numberFields[i][j].getBackground() == Color.white){
                        numberFields[i][j].setText("");
                    }
                }
            }
        }
        
        
/*        for (int kol = 0; kol <= 8; kol++) {
            for (int rad = 0; rad <= 8; rad++) {
                rader[rad][kol].setValue((rad / 3) * 3 + (kol/3));
            }
        }
        
        for (int i = 0; i <= 8; i++) {
            for (int j = 0; j <= 8; j++) {
                textRutor[i][j].setText(rutor[i][j].toString());
            }
        }
*/        
        
        



    }
}











